<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue';

import { Page } from '@vben/common-ui';

import {
  Avatar,
  Button,
  Card,
  Input,
  List,
  message,
  Tabs,
} from 'ant-design-vue';

import { aiAnalyzeImage } from '#/api/ai/ai';
import Upload from '#/components/form/components/upload.vue';
import { Icon } from '#/components/icon';

/* 导入共享组件 */
import { Empty as EmptyComponent, Loading } from '../components';
/* 导入共享的主题组合式函数 */

/* 组件状态 */
const loading = ref(false);
const activeTab = ref('imageAnalysis');
const imageUrl = ref('');
const analysisResult = ref('');
const question = ref('');
const imageQuestions = ref<string[]>([]);
const imageAnswers = ref<string[]>([]);

/* 初始化 */
onMounted(() => {
  /* 主题已经在useTheme中自动处理了，不需要额外初始化 */
});

/* 图片URL更新处理 */
const handleImageUpdate = (url: string) => {
  imageUrl.value = url;
  message.info('图片URL已更新');
};

/* 监听imageUrl变化 */
watch(imageUrl, (newUrl) => {
  if (newUrl) {
    message.success('图片URL有效，可以进行分析或提问');
  }
});

/* 图像分析 */
const handleAnalyzeImage = async () => {
  if (!imageUrl.value) {
    message.warning('请先上传图片');
    return;
  }

  /* 显示当前图片URL */
  message.info('正在分析图片...');
  loading.value = true;

  try {
    /* 调用图片分析接口，不传递prompt参数 */
    const result = await aiAnalyzeImage(imageUrl.value, '');
    analysisResult.value = result;
  } catch (error: any) {
    message.error(`分析失败: ${error.message || '未知错误'}`);
    console.error('图像分析错误:', error);
  } finally {
    loading.value = false;
  }
};

/* 图像问答 */
const handleAskAboutImage = async () => {
  if (!imageUrl.value) {
    message.warning('请先上传图片');
    return;
  }

  if (!question.value.trim()) {
    message.warning('请输入问题');
    return;
  }

  loading.value = true;
  const currentQuestion = question.value;
  imageQuestions.value = [...imageQuestions.value, currentQuestion];

  try {
    /* 调用图片分析接口，传递prompt参数(用户问题) */
    const answer = await aiAnalyzeImage(imageUrl.value, currentQuestion);
    imageAnswers.value = [...imageAnswers.value, answer];
  } catch (error: any) {
    imageAnswers.value = [
      ...imageAnswers.value,
      `提问失败: ${error.message || '未知错误'}`,
    ];
    console.error('视觉问答错误:', error);
  } finally {
    loading.value = false;
    question.value = '';
  }
};

/* 清除当前图片和分析结果 */
const handleClear = () => {
  imageUrl.value = '';
  analysisResult.value = '';
  imageQuestions.value = [];
  imageAnswers.value = [];
  message.success('已清除');
};
</script>

<template>
  <Page auto-content-height>
    <Card :bordered="false" class="ai-card">
      <Tabs v-model:active-key="activeTab">
        <Tabs.TabPane key="imageAnalysis" tab="图像分析">
          <div class="responsive-container">
            <!-- 左侧上传区域 -->
            <div class="left-section">
              <Card class="upload-card">
                <div class="upload-area">
                  <Upload
                    v-model="imageUrl"
                    list-type="picture-card"
                    class="image-uploader"
                    :disabled="loading"
                    @update:model-value="handleImageUpdate"
                  />
                </div>
                <div class="form-actions">
                  <Button
                    type="primary"
                    :disabled="!imageUrl"
                    :loading="loading"
                    @click="handleAnalyzeImage"
                    class="animated-button"
                    style="margin-right: 8px"
                  >
                    <Icon icon="ant-design:search-outlined" />
                    分析图像
                  </Button>
                  <Button
                    :disabled="!imageUrl"
                    @click="handleClear"
                    class="animated-button"
                  >
                    <Icon icon="ant-design:clear-outlined" />
                    清除
                  </Button>
                </div>
              </Card>
            </div>

            <!-- 右侧分析结果 -->
            <div class="right-section">
              <Card title="分析结果" class="result-card">
                <Loading
                  v-if="loading"
                  text="正在分析图像..."
                  sub-text="AI正在理解图像内容"
                />

                <template v-else-if="analysisResult">
                  <div class="analysis-result">
                    <div class="result-content">
                      {{ analysisResult }}
                    </div>
                  </div>
                </template>

                <EmptyComponent
                  v-else
                  icon="ant-design:file-image-outlined"
                  text="暂无分析结果"
                  tips="上传图片并点击分析按钮，获取AI图像分析结果"
                />
              </Card>
            </div>
          </div>
        </Tabs.TabPane>

        <Tabs.TabPane key="visualQA" tab="视觉问答">
          <div class="responsive-container">
            <!-- 左侧区域 -->
            <div class="left-section">
              <Card>
                <div class="upload-area">
                  <Upload
                    v-model="imageUrl"
                    list-type="picture-card"
                    class="image-uploader"
                    :disabled="loading"
                    @update:model-value="handleImageUpdate"
                  />
                </div>

                <div class="form-item">
                  <div class="form-label">问题</div>
                  <Input.TextArea
                    v-model:value="question"
                    placeholder="请输入关于图片的问题..."
                    :rows="3"
                    :disabled="loading || !imageUrl"
                  />
                </div>

                <div class="form-actions">
                  <Button
                    type="primary"
                    :disabled="!imageUrl || !question.trim()"
                    :loading="loading"
                    @click="handleAskAboutImage"
                    class="animated-button"
                    style="margin-right: 8px"
                  >
                    <Icon icon="ant-design:question-circle-outlined" />
                    提问
                  </Button>
                  <Button
                    :disabled="!imageUrl"
                    @click="handleClear"
                    class="animated-button"
                  >
                    <Icon icon="ant-design:clear-outlined" />
                    清除
                  </Button>
                </div>
              </Card>
            </div>

            <!-- 右侧问答结果 -->
            <div class="right-section">
              <Card title="问答历史" class="result-card">
                <Loading
                  v-if="loading"
                  text="正在思考中..."
                  sub-text="AI正在分析图像并回答问题"
                />

                <List
                  v-else-if="imageQuestions.length > 0"
                  class="qa-list"
                  :data-source="imageQuestions"
                >
                  <template #renderItem="{ item, index }">
                    <List.Item>
                      <div class="qa-item">
                        <div class="qa-question">
                          <Avatar class="avatar user-avatar">
                            <template #icon>
                              <Icon icon="ant-design:user-outlined" />
                            </template>
                          </Avatar>
                          <div class="qa-content">
                            <div class="qa-header">
                              <span class="user-name">用户</span>
                            </div>
                            <div class="qa-text">{{ item }}</div>
                          </div>
                        </div>

                        <div class="qa-answer" v-if="imageAnswers[index]">
                          <Avatar class="avatar ai-avatar">
                            <template #icon>
                              <Icon icon="ant-design:robot-outlined" />
                            </template>
                          </Avatar>
                          <div class="qa-content">
                            <div class="qa-header">
                              <span class="ai-name">AI助手</span>
                            </div>
                            <div class="qa-text">
                              {{ imageAnswers[index] }}
                            </div>
                          </div>
                        </div>
                      </div>
                    </List.Item>
                  </template>
                </List>

                <EmptyComponent
                  v-else
                  icon="ant-design:message-outlined"
                  text="暂无问答记录"
                  tips="上传图片并提问，AI将帮你解答图片相关的问题"
                />
              </Card>
            </div>
          </div>
        </Tabs.TabPane>
      </Tabs>
    </Card>
  </Page>
</template>

<style lang="less" scoped>
// 引入通用样式和主题变量
@import '../styles/common.less';
@import '../styles/theme.less';

// 多模态页面特定样式
.upload-card,
.result-card {
  height: 100%;
  margin-bottom: 0;
}

.upload-area {
  display: flex;
  justify-content: center;
  margin-bottom: 16px;
}

.image-uploader {
  max-width: 100%;
  margin: 0 auto;
}

.analysis-result {
  padding: 16px;
  background-color: var(--card-bg);
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);

  .result-content {
    line-height: 1.6;
    color: var(--text-color);
    white-space: pre-wrap;
  }
}

// 问答样式
.qa-list {
  max-height: 600px;
  padding: 0 8px;
  overflow-y: auto;
}

.qa-item {
  display: flex;
  flex-direction: column;
  gap: 16px;
  width: 100%;
}

.qa-question,
.qa-answer {
  display: flex;
  gap: 12px;
  width: 100%;
}

.avatar {
  flex-shrink: 0;
  box-shadow: 0 2px 8px rgb(0 0 0 / 20%);
}

.user-avatar {
  background-color: #722ed1;
}

.ai-avatar {
  background-color: #1890ff;
}

.qa-content {
  flex: 1;
  padding: 12px;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgb(0 0 0 / 10%);
}

.qa-header {
  margin-bottom: 8px;
}

.user-name {
  padding: 2px 8px;
  font-size: 12px;
  color: var(--username-color);
  background-color: var(--username-bg);
  border-radius: 4px;
}

.ai-name {
  padding: 2px 8px;
  font-size: 12px;
  color: var(--model-tag-color);
  background-color: var(--model-tag-bg);
  border-radius: 4px;
}

.qa-text {
  line-height: 1.6;
  color: var(--text-color);
  white-space: pre-wrap;
}

.qa-question .qa-content {
  background-color: var(--user-msg-bg);
  border: 1px solid var(--user-msg-border);
}

.qa-answer .qa-content {
  background-color: var(--ai-msg-bg);
  border: 1px solid var(--ai-msg-border);
}
</style>
